package io.renren.modules.bug.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.*;
import io.renren.modules.bug.dao.BugDao;
import io.renren.modules.bug.entity.BugEntity;
import io.renren.modules.bug.entity.BugStatusEntity;
import io.renren.modules.bug.enums.BugStatusEnums;
import io.renren.modules.bug.service.BugService;
import io.renren.modules.bug.service.BugStatusService;
import io.renren.modules.bug.vo.BugResVo;
import io.renren.modules.bug.vo.BugVo;
import io.renren.modules.bug.vo.ExportBugReqVo;
import io.renren.modules.bug.vo.ExportBugVo;
import io.renren.modules.module.entity.Module;
import io.renren.modules.module.entity.ModuleBug;
import io.renren.modules.module.service.ModuleBugService;
import io.renren.modules.module.service.ModuleServicex;
import io.renren.modules.product.entity.ProductEntity;
import io.renren.modules.product.service.ProductService;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.test.usecase.entity.UseCase;
import io.renren.modules.test.usecase.entity.UseCaseLibrary;
import io.renren.modules.test.usecase.service.CaseLibraryService;
import io.renren.modules.test.usecase.service.CaseService;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;


@Service("bugService")
public class BugServiceImpl extends ServiceImpl<BugDao, BugEntity> implements BugService {
    @Autowired
    private ModuleBugService moduleBugService;
    @Autowired
    private BugDao bugDao;
    @Autowired
    private BugStatusService bugStatusService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ModuleServicex moduleServicex;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BugEntity> page = this.page(
                new Query<BugEntity>().getPage(params),
                new QueryWrapper<BugEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新建缺陷
     *
     * @param bugVo
     */
    @Override
    @Transactional
    public void saveOrUpdate(BugVo bugVo) {
        // 1. 拷贝bug属性
        BugEntity bugEntity = new BugEntity();
        BeanUtils.copyProperties(bugVo, bugEntity);
        // 2. bm_r_module_bug
        ModuleBug moduleBug = new ModuleBug();
        BeanUtils.copyProperties(bugVo, moduleBug);
        if (bugVo.getBugId() == null) {
            this.save(bugEntity);
            moduleBug.setBugId(bugEntity.getBugId());
            moduleBugService.save(moduleBug);
        } else { // 修改
            this.updateById(bugEntity);
            moduleBugService.updateById(moduleBug);
        }
    }

    /**
     * 分页复合查询bug信息
     *
     * @param params
     * @param status
     * @param productId
     * @param moduleId
     * @return
     */
    @Override
    public PageUtils compoundQueryBugInfoPage(Map<String, Object> params, Integer status,
                                              Long productId, Long moduleId) {

        QueryWrapper<BugEntity> bugEntityQueryWrapper = new QueryWrapper<>();
        // 根据bug状态
        if (!StringUtils.isEmpty(status)) {
            bugEntityQueryWrapper.eq("bug_status", status);
        }
        // 获取参数key，可以根据bugId 或 bug名称查询
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            bugEntityQueryWrapper.and(item -> {
                item.eq("bug_id", key).or().like("bug_name", key);
            });
        }
        List<BugEntity> bugEntities = this.list(bugEntityQueryWrapper);
        List<Long> modIds = new ArrayList<>();
        QueryWrapper<Module> moduleQueryWrapper = new QueryWrapper<>();
        // 根据 模块Id -> bugId
        if (!StringUtils.isEmpty(moduleId)) {
            modIds.add(moduleId);
        } else if (!StringUtils.isEmpty(productId)) {// 根据 产品id -> 模块id -> bugId
            moduleQueryWrapper.eq("product_id", productId);
            List<Module> modules = moduleServicex.list(moduleQueryWrapper);
            // 收集所有modId
            modIds = modules.stream().map(item -> {
                return item.getModuleId();
            }).collect(Collectors.toList());
        }
        QueryWrapper<ModuleBug> moduleBugQueryWrapper = new QueryWrapper<>();
        List<Long> bugIds = null;
        if ((bugEntities != null && bugEntities.size() > 0) || bugEntities.size() > 0) {
            bugIds = bugEntities.stream().map(item -> {
                return item.getBugId();
            }).collect(Collectors.toList());
            moduleBugQueryWrapper.in("bug_id", bugIds);
        }
        if (modIds != null && modIds.size() > 0) {
            moduleBugQueryWrapper.in("module_id", modIds);
        }
        // 分页查询
        IPage<ModuleBug> page01 = moduleBugService.page(
                new Query<ModuleBug>().getPage(params),
                moduleBugQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page01);
        List<ModuleBug> moduleBugs = page01.getRecords();
        if (moduleBugs.size() > 0) {
            bugIds = moduleBugs.stream().map(item -> {
                return item.getBugId();
            }).collect(Collectors.toList());
        }
        if (bugIds == null) {
            bugEntityQueryWrapper.in("bug_id", "");
        } else {
            bugEntityQueryWrapper.in("bug_id", bugIds);
        }
        final List<BugEntity> records = this.list(bugEntityQueryWrapper);
        // 根据 bugId 获取 模块Id 以及 开发负责人Id
        moduleBugQueryWrapper = new QueryWrapper<>();
        List<Long> bugIds01 = null;
        List<ModuleBug> moduleBugs1 = null;
        // pmub_Id
        List<Long> mubIds = null;
        if (records.size() > 0 && moduleBugs.size() > 0) {
            bugIds01 = records.stream().map(item -> {
                return item.getBugId();
            }).collect(Collectors.toList());
            mubIds = moduleBugs.stream().map(item -> {
                return item.getMbId();
            }).collect(Collectors.toList());
            List<BugResVo> bugInfo = bugDao.getBugInfo(mubIds);
            System.out.println("bugInfo  =====>" + bugInfo);
            List<BugResVo> bugInfo01 = bugInfo.stream().map(item -> {
                for (BugEntity bugEntity : records) {
                    if (item.getBugId() == bugEntity.getBugId()) {
                        BeanUtils.copyProperties(bugEntity, item);
                    }
                }
                return item;
            }).collect(Collectors.toList());


            SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
            if (sysUserEntity.getUsername().equals("admin")) {
                pageUtils.setList(bugInfo01);
                return pageUtils;
            }
            ;
            //获取userid
            Long userId = sysUserEntity.getUserId();
            //获取当前用户的角色
            SysUserRoleEntity sysUserRoleServiceOne = sysUserRoleService.getOne(new LambdaQueryWrapper<SysUserRoleEntity>()
                    .eq(SysUserRoleEntity::getUserId, userId));
            Long roleId = sysUserRoleServiceOne.getRoleId();
            SysRoleEntity role = sysRoleService.getById(roleId);
            String roleName = role.getRoleName();

            pageUtils.setList(bugInfo01.stream()
                    .filter(item -> roleName.equals("产品经理") || item.getCreateUser().equals(userId) || item.getBugPrincipal().equals(userId))
                    .collect(Collectors.toList()));
            return pageUtils;
        }

        return null;
    }

    @Override
    @Transactional
    public void updateStatus(Long bugId, Integer status) {
        // 1. 修改 bug 表
        BugEntity bugEntity = new BugEntity();
        bugEntity.setBugId(bugId);
        bugEntity.setBugStatus(status);
        QueryWrapper<BugEntity> bugEntityQueryWrapper = new QueryWrapper<>();
        bugEntityQueryWrapper.eq("bug_id", bugId);
        boolean update = this.update(bugEntity, bugEntityQueryWrapper);
        // 2. 修改 bug 状态表
        BugStatusEntity bugStatusEntity = new BugStatusEntity();
        bugStatusEntity.setBsStatus(status);
        boolean save = bugStatusService.save(bugStatusEntity);
        if (!update && !save) {
            throw new RuntimeException("修改状态失败");
        }
    }

    @Override
    @Transactional
    public void deleteById(Long bugId) {
        // 1. 删除 bug 表
        boolean bugFlag = this.removeById(bugId);
        // 2. 删除 关联表
        QueryWrapper<ModuleBug> moduleBugQueryWrapper = new QueryWrapper<>();
        moduleBugQueryWrapper.eq("bug_id", bugId);
        boolean pmubFlag = moduleBugService.remove(moduleBugQueryWrapper);
        if (!bugFlag && !pmubFlag) {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public BugResVo infoById(Long bugId, Long rmbId) {
        // 1. 查询bug基本信息
        BugEntity bugEntity = this.getById(bugId);
        System.out.println("bug ===========>" + bugEntity);
        // 2. 查询关联表
        QueryWrapper<ModuleBug> moduleBugQueryWrapper = new QueryWrapper<>();
        moduleBugQueryWrapper.eq("mb_id", rmbId);
        ModuleBug moduleBug = moduleBugService.getOne(moduleBugQueryWrapper);
        // 2.1 根据模块id查询模块名称
        Module moduleEntity = moduleServicex.getById(moduleBug.getModuleId());
        // 2.2 根据产品查询产品名称
        ProductEntity productEntity = productService.getById(moduleEntity.getProductId());
        // 2.3 根据用户id查询用户名称
        SysUserEntity sysUserEntity = sysUserService.getById(moduleBug.getBugPrincipal());
        // 封装返回的对象
        BugResVo bugResVo = new BugResVo();
        BeanUtils.copyProperties(bugEntity, bugResVo);
        bugResVo.setUserName(sysUserEntity.getUsername());
        bugResVo.setProductName(productEntity.getProductName());
        bugResVo.setModuleName(moduleEntity.getModuleName());
        bugResVo.setProductId(productEntity.getProductId());
        BeanUtils.copyProperties(moduleBug, bugResVo);
        System.out.println("modid ====>" + moduleEntity.getModuleId());
        return bugResVo;
    }
    /**
     *         productId: "",
     *         moduleId: "",
     *         bugCreateUser: '',
     *         bugSolveUser: '',
     *         bugStatus: "",
     *         bugStartTime: "",
     *         bugEndTime: "",
     */
    @Override
    public List<ExportBugVo> exportExcelInfo(ExportBugReqVo exportBugReqVo) {
        Long productId = exportBugReqVo.getProductId();
        Long moduleId = exportBugReqVo.getModuleId();
        Long bugCreateUser = exportBugReqVo.getBugCreateUser();
        Long bugSolveUser = exportBugReqVo.getBugSolveUser();
        Integer bugStatus = exportBugReqVo.getBugStatus();
        Date bugStartTime = exportBugReqVo.getBugStartTime();
        Date bugEndTime = exportBugReqVo.getBugEndTime();
        //先查询出所有的缺陷列表
        List<BugEntity> bugList = this.list();
        //过滤缺陷
        if (productId != null){
            List<Long> bugIds = baseMapper.getBugIdByProductId(productId);
            if (bugIds !=null && bugIds.size() > 0){
                bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
            }
        }
        if (moduleId != null){
            List<Long> bugIds = baseMapper.getBugIdByModuleId(moduleId);
            if (bugIds !=null && bugIds.size() > 0){
                bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
            }
        }
        if (bugCreateUser != null){
            List<Long> bugIds = baseMapper.getBugIdByCreateUser(bugCreateUser);
            bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
        }
        if (bugSolveUser!=(null)){
            List<Long> bugIds = baseMapper.getBugIdBySolveUser(bugSolveUser);
            bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
        }
        if (bugStatus!=null){
            List<Long> bugIds = baseMapper.getBugIdByStatus(bugStatus);
            bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
        }
        if (bugStartTime!=null){
            List<Long> bugIds = baseMapper.getBugIdByStartTime(bugStartTime);
            bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
        }
        if (bugEndTime!=null){
            List<Long> bugIds = baseMapper.getBugIdByEndTime(bugEndTime);
            bugList = bugList.stream().filter(bug -> bugIds.contains(bug.getBugId())).collect(Collectors.toList());
        }

        List<ExportBugVo> export = bugList.stream().map(bug -> {
            ExportBugVo exportBugVo = new ExportBugVo();
            BeanUtils.copyProperties(bug, exportBugVo);
            // setBugCreateUser
            exportBugVo.setBugCreateUser(sysUserService.getById(bug.getCreateUser()).getUsername());
            //bugSolveUser
            ModuleBug moduleBug = moduleBugService.getOne(new LambdaUpdateWrapper<ModuleBug>()
                    .eq(ModuleBug::getBugId, bug.getBugId()));
            exportBugVo.setBugSolveUser(sysUserService.getById(moduleBug.getBugPrincipal()).getUsername());
            //productName
            exportBugVo.setProductName(productService
                    .getById(moduleServicex
                            .getById(moduleBug.getModuleId())
                            .getProductId()).getProductName());
            //moduleName
            exportBugVo.setModuleName(moduleServicex.getById(moduleBug.getModuleId()).getModuleName());
            exportBugVo.setBugDes(bug.getBugDesc());
            // bugStatus
            BugStatusEnums statusEnums =  BugStatusEnums.getByCode(bug.getBugStatus());

            exportBugVo.setStatus(statusEnums.getStatusName());
            return exportBugVo;
        }).collect(Collectors.toList());
        System.out.println(export);
        return export;
    }

/*    @Override
    public List<ExportBugReqVo> getExportInfo(Long testId) {
        // 1. 根据测试人员Id获取模块Id
        QueryWrapper<UseCase> useCaseQueryWrapper = new QueryWrapper<>();
        useCaseQueryWrapper.eq("test_user", testId);
        List<UseCase> useCaseLibraries = caseService.list(useCaseQueryWrapper);
        if (useCaseLibraries != null && useCaseLibraries.size() > 0) {
            // 收集模块Id
            List<Long> modIds = useCaseLibraries.stream().map(item -> {
                return item.getModuleId();
            }).collect(Collectors.toList());
            // 2. 根据模块Id，查询产品
            QueryWrapper<Module> moduleQueryWrapper = new QueryWrapper<>();
            moduleQueryWrapper.in("module_id", modIds);
            List<Module> modules = moduleServicex.list(moduleQueryWrapper);
            List<Long> productIds = modules.stream().map(item -> {
                return item.getProductId();
            }).collect(Collectors.toList());
            //  根据pid查询产品
            List<ProductEntity> productEntities = productService.listByIds(productIds);
            List<ExportBugReqVo> exportBugReqVos = productEntities.stream().map(item -> {
                ExportBugReqVo exportBugReqVo = new ExportBugReqVo();
                BeanUtils.copyProperties(item, exportBugReqVo);
                List<Module> modules1 = new ArrayList<>();
                for (Module module : modules) {
                    if (module.getProductId() == item.getProductId()) {
                        modules1.add(module);
                    }
                }
                exportBugReqVo.setModules(modules1);
                return exportBugReqVo;
            }).collect(Collectors.toList());
            return exportBugReqVos;
        } else {
            return null;
        }
    }*/

    private String desktopPath() {
        String osName = System.getProperty("os.name").toLowerCase();
        String userHome = System.getProperty("user.home");
        String desktopPath = "";
        if (osName.contains("win")) {
            // Windows系统
            desktopPath = userHome + "\\Desktop";
        } else if (osName.contains("mac")) {
            // macOS系统
            desktopPath = userHome + "\\Desktop";
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix")) {
            // Unix/Linux系统
            desktopPath = userHome + "\\Desktop";
        } else {
            // 未知系统，使用默认路径
            desktopPath = userHome + "\\Desktop";
        }
        return desktopPath;
    }

}